package com.sl.crawler.robot.output.impl;

import com.opencsv.CSVWriter;
import com.sl.crawler.common.utils.object.ConvertUtils;
import com.sl.crawler.robot.CrawlerConfig;
import com.sl.crawler.robot.output.IOutput;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;

/**
 * Created by shiling on 2017/6/9.
 */
public class CsvOutput implements IOutput {
    private final static Logger LOG = LoggerFactory.getLogger(CsvOutput.class);

    public static void outputMapList(List<Map<String, String>> list, String filePath) {
        List<String[]> csvList = ConvertUtils.mapListToArrayList(list);
        output(csvList, filePath);
    }

    public static void output(List<String[]> list, String filePath) {
        try {
            File file = new File(filePath);
            FileUtils.forceMkdirParent(file);
        } catch (Exception e) {
            LOG.error("创建文件父目录失败!filePath=" + filePath, e);
        }
        try (BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "GBK"))) {
            CSVWriter csvWriter = new CSVWriter(br, ',');
            for (String[] csvLine : list) {
                csvWriter.writeNext(csvLine);
            }
        } catch (Exception e) {
            LOG.error("写文件失败!" + e);
        }
    }

    @Override
    public void output(List<Map<String, String>> list, CrawlerConfig crawlerConfig) {
        List<String[]> csvList = ConvertUtils.mapListToArrayList(list);
        output(csvList, crawlerConfig.getOutputCsvPath());
    }
}
